/*
 * @Author: 麦冬果果
 * @Date: 2021-09-03 16:55:56
 * @LastEditTime: 2021-09-11 09:40:11
 * @LastEditors: 麦冬果果
 * @Description: 文件描述
 * @FilePath: /web/src/permission.js
 * 可以输入预定的版权声明、个性签名、空行等
 */
import router from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {
  getToken
} from '@/utils/auth'

NProgress.configure({
  showSpinner: false
})

//const whiteList = ['http://localhost:1024/login', '/auth-redirect', '/bind', '/register']

router.beforeEach((to, from, next) => {
  NProgress.start()
  console.log("getToken()", getToken())
  if (getToken()) { //
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
    if (to.path === '/login') {
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => {
          next({
            ...to,
            replace: true
          })
          // store.dispatch('GenerateRoutes').then(accessRoutes => {
          //   // 根据roles权限生成可访问的路由表
          //   router.addRoutes(accessRoutes) // 动态添加可访问路由表
          //   next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          // })
        }).catch(err => {
          store.dispatch('LogOut').then(() => {
            Message.error(err)
            window.location.href = "about:blank";
            window.close();
          })
        })
      } else {
        next()
      }
    }
  } else {
    window.open("http://主服务登录地址", "_blank") //?redirect=${redirect}
    NProgress.done()

  }
})

router.afterEach(() => {
  NProgress.done()
})
